package com.zn.listener;


import com.alibaba.fastjson.JSONObject;
import com.zn.socketReceiver.SocketHandler;
import com.zn.util.Constant;
import com.zn.util.GZIPUtils;
import com.zn.vo.*;
import com.zn.web.rpc.MdRemoteCall;
import com.zn.websocket.group.ChannelGroups;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 订阅到redis消息
 */
@Component
public class RedisReceiver {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisReceiver.class);

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private MdRemoteCall mdRemoteCall;

    public void tradeReportNotify(String mapToJson) {
        try {
            JSONObject json = JSONObject.parseObject(mapToJson);
            String data=json.get("data").toString();
            String uuid=json.get("uuid").toString();
            LOGGER.warn("接受到交易过来的回报数据：" + mapToJson);
            //将回报数据推送给客户端 以二进制推送 推送压缩后的包
            byte [] byteData= GZIPUtils.compress(data.toString());
            ByteBuf byteBuf = Unpooled.buffer(byteData.length * 3);
            byteBuf.writeBytes(byteData);
            ChannelGroups.writeByUuid(uuid, new BinaryWebSocketFrame(byteBuf));
            String jieya=GZIPUtils.uncompressToString(byteData);
            LOGGER.warn("tradeReportNotify 解压后的数据包" + jieya);
        }catch (Exception e){
            LOGGER.error("tradeReportNotify Exception.......",e);
        }
    }

    /**
     * 监听crm发送过来的 新增的参考行情
     * @param code
     */
    public void addReferMdNotify(String code){
        String referMdInfoApiStr = mdRemoteCall.getReferMdInfo(code);
        String[] etfMdInfos = mdRemoteCall.subStringSinaData(referMdInfoApiStr);
        if (etfMdInfos != null) {
            ////var hq_str_s_sh510050="50ETF,2.453,0.011,0.45,2836180,69702";
            EtfMdInfo etfMdInfo = new EtfMdInfo(etfMdInfos[0], etfMdInfos[1], etfMdInfos[3],etfMdInfos[2],  etfMdInfos[4], etfMdInfos[5]);
            Object jsonMd = JSONObject.toJSON(etfMdInfo);
            redisTemplate.opsForHash().put(Constant.SINA_REFER_MD_LIST, code, jsonMd.toString());
        }
    }

    public void replyCustomerMessage(String customerId){
        try {
            LOGGER.info("replyCustomerMessage--------->" + customerId);
            Map<String,Object> messageMap=new HashMap<String,Object>();
            messageMap.put("messageNum", 1);
            SocketJsonData socketJsonData=new SocketJsonData(Constant.MESSAGE,JSONObject.toJSON(messageMap));
            Object messagePush= JSONObject.toJSON(socketJsonData);
            byte [] byteData= GZIPUtils.compress(messagePush.toString());
            ByteBuf byteBuf = Unpooled.buffer(byteData.length * 3);
            byteBuf.writeBytes(byteData);
            ChannelGroups.writeByUuid(customerId, new BinaryWebSocketFrame(byteBuf));
            String jieya=GZIPUtils.uncompressToString(byteData);
            LOGGER.warn("replyCustomerMessage 解压后的数据包" + jieya);
        }catch (Exception e){
            LOGGER.error("replyCustomerMessage is error",e);
        }
    }

    /**
     * 置空
     * @param emptyTypeStr 1:交易 2：行情 3：都发生变动
     */
    public void updateSocketInfo(String emptyTypeStr){
        try {
            Integer emptyType=Integer.valueOf(emptyTypeStr);
            /**防止出现置空时 任然时旧对象数据**/
            Thread.sleep(3000);
            LOGGER.warn("empty------->" + emptyType);
            /**socket对象置空**/
            if(2==emptyType || 3==emptyType){
                SocketHandler.setEmpty();
            }
        }catch (Exception e){
            LOGGER.error("updateSocketInfo----->"+e.getMessage());
        }
    }

    public void bestsignRegisterStatusNotify(String jsonStr){
        try {
            LOGGER.warn("bestsignRegisterStatusNotify：" + jsonStr);
            JSONObject json = JSONObject.parseObject(jsonStr);
            String customerId=json.get("customerId").toString();
            SocketJsonData socketJsonData=new SocketJsonData(Constant.BESTSIGN_REGISTER,JSONObject.toJSON(jsonStr));
            Object messagePush= JSONObject.toJSON(socketJsonData);
            byte [] byteData= GZIPUtils.compress(messagePush.toString());
            ByteBuf byteBuf = Unpooled.buffer(byteData.length * 3);
            byteBuf.writeBytes(byteData);
            ChannelGroups.writeByUuid(customerId, new BinaryWebSocketFrame(byteBuf));
            String jieya=GZIPUtils.uncompressToString(byteData);
            LOGGER.warn("bestsignRegisterStatusNotify 解压后的数据包" + jieya);
        }catch (Exception e){
            LOGGER.error("bestsignRegisterStatusNotify-->",e);
        }

    }

}